package arcade;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import util.TraitFactory;

/**
 * Player
 * 
 * The player is a special role player which represents the user. The player
 * contains traits which can be converted to a string and shown on-screen.
 * Players can only have a single trait of any given role.
 * 
 * In addition players provide a means to modify traits. Through the player
 * interface other classes can modify traits without worrying about whether the
 * traits already exist, or what their values are.
 * 
 * @author Alexander Schearer <aas11@duke.edu>
 */
public class Player extends RolePlayer implements Iterable<Trait> {

	private List<Trait> myTraits;

	public Player(String role) {
		super(role);
		myTraits = new ArrayList<Trait>();
	}

	/**
	 * Add a new trait to the player
	 * 
	 * If the trait is already added then it will not be added again and false
	 * will be returned.
	 * 
	 * @param t
	 * @return
	 */
	public boolean assignTrait(Trait t) {
		if (myTraits.contains(t))
			return false;
		return myTraits.add(t);
	}

	/**
	 * Remove an existing trait
	 * 
	 * @param t
	 * @return
	 */
	public boolean removeTrait(Trait t) {
		return myTraits.remove(t);
	}

	/**
	 * Update a specified trait with a given value
	 * 
	 * If the trait does not exist attempt to create the trait using the trait
	 * factory. If the trait cannot be created then return false, else update
	 * the new trait, add it to the list of existing traits, and return true.
	 * 
	 * @param role
	 * @param value
	 * @return
	 */
	public boolean updateTrait(String role, int value) {
		for (Trait toUpdate : this) {
			if (toUpdate.equals(role)) {
				toUpdate.update(value);
				return true;
			}
		}
		try {
			Trait newTrait = TraitFactory.getInstance(role);
			newTrait.update(value);
			myTraits.add(newTrait);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public Iterator<Trait> iterator() {
		return myTraits.iterator();
	}

}
